function showUsersList()
{
    $.getJSON("/app/rest/users", function(data)
    {
        $('#message')[0].innerHTML = "";
        $.each(data, function(i, n)
        {
            if (i == 0)
            {
                $("#userTemplateHeader").tmpl(n).appendTo("#message");
            }
            var tableRow = $("#userTemplate").tmpl(n).appendTo("#message");
            $("#message tr:even").addClass("alt");
            $("td.actions > input[id='editbutton']", tableRow).bind('click', n["userName"], userEditActionHandler);
            $("td.actions > input[id='deletebutton']", tableRow).bind('click', n["userName"], userDeleteActionHandler);
        });
    });
}
$(document).ready(function()
{
    showUsersList();
    $('#adddisplay').click(function ()
    {
        $('#addformdiv').show();
        $('#adduser').click(function ()
        {
            addUser();
            return false;
        });
        $('#addform input[name="cancel"]').click(function(event)
        {
            $('#addformdiv').hide();
        });
    });
});


function addUser()
{
    var valid = $('#addform').validate().form();
    var sa = $("#addform").serializeArray();
    if (valid)
    {
        var formVal = formToJSON(sa)
        $.ajax({
            type: "POST",
            async:true,
            contentType:"application/json",
            url: "/app/rest/user",
            data: JSON.stringify(formVal),
            processData: false,
            dataType: "json"
        }).success(function(msg)
        {
            var input = $("input:reset");
            clear_form_elements('#addformdiv');
            $('#addformdiv').hide();
            showUsersList();
        });
    }
}

function clear_form_elements(formelement)
{
    $(formelement).find(':input').each(function()
    {
        switch (this.type)
        {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });
}

function userDeleteActionHandler(event)
{
    var userName = event.data;
    $.ajax(
    {
        type:"DELETE",
        async:true,
        //            contentType:"application/json",
        url:"/app/rest/user/" + userName,
        processData:false,
        dataType:"json"
    }
            ).success(function(msg)
    {
        showUsersList();
    });


}

function userEditActionHandler(event)
{
    $("#addformdiv").hide();
    $.getJSON("/app/rest/user/" + event.data, function(data)
    {
        $("#editform input[name='userName']").val(data["userName"]);
        $("#editform input[name='firstName']").val(data["firstName"]);
        $("#editform input[name='lastName']").val(data["lastName"]);
        $("#editform input[name='phone']").val(data["phone"]);
        $("#editform input[name='email']").val(data["email"]);
        $("#editform input[name='city']").val(data["city"]);
        $("#editform input[name='age']").val(data["age"]);
    });
    $("#userformdiv").show();
    $("#editform input[name='update']").bind('click', function(event)
    {
        var userForm = $("#editform");
        var valid = $('#editform').validate().form();
        if (valid)
        {
            var formElements = userForm.serializeArray();
            var data = formToJSON(formElements);
            $.ajax(
            {
                type:"POST",
                async:true,
                contentType:"application/json",
                url:"/app/rest/user/" + data["userName"],
                data: JSON.stringify(data),
                processData:false,
                dataType:"json"
            }
                    ).success(function(msg)
            {
                $("#userformdiv").hide();
                showUsersList();
            });
        }
    });

    $("#editform input[name='cancel']").bind('click', function(event)
    {
        $('#userformdiv').hide();
    });
}

function formToJSON(a)
{
    var o = {};
    $.each(a, function()
    {
        if (o[this.name] != undefined)
        {
            if (!o[this.name].push)
            {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
            //alert(this.value || '');
        }
        else
        {
            o[this.name] = this.value || '';
            //alert(this.value || '');

        }
    });
    return o;
}
